<?php
error_reporting(E_ALL);

include_once 'common_classes.php';
include_once 'results_grid.php';
include_once 'config.php';

$hasStarted = false;
$grid;

function getGrid() {
	global $hasStarted;
	
	if(!$hasStarted)
		session_start();
	
	$hasStarted = true;
	
	$grid = unserialize($_SESSION['grid']);
	return $grid;
}

function getWithinPercent($percent) {
	if($percent > 99 || $percent < 0)
		$percent = 5;
		
	$grid = getGrid();
	
	// [x][0] Name
	// [x][1] Description
	// [x][2] URL
	// [x][3] percentage
	// [x][4] real name
	// [x][5] userid
	$returnarray[0][0] = 0;
	
	$rankings = $grid->getRankings();
	$count = count($rankings);
	
	
	$k = 0;
	
	// skip the first entry because that is 'Your answers'
	$topscore = $rankings[1][1];
	for($i = 1; $i < $count; $i++) {
		
		$candidate = $rankings[$i][0];
		$name = $candidate->getName();
		$description = $candidate->getDescription();
		$url = $candidate->getURL();
		$realname = $candidate->getRealName();
		$userid = $candidate->getUserID();
		$corp = $candidate->getCorp();
		$alliance = $candidate->getAlliance();
		$total = $rankings[$i][1];
		//echo 'woei: ' . $topscore . ' ' . $total . ' ' . isWithinFivePercent($topscore, $total) . '<br />';
		if(isWithinPercent($topscore, $total, $percent)) {
			$returnarray[$k][0] = $name;
			$returnarray[$k][1] = $description;
			$returnarray[$k][2] = $url;
			$returnarray[$k][3] = getPercentage($total);
			$returnarray[$k][4] = $realname;
			$returnarray[$k][5] = $userid;
			$returnarray[$k][6] = $corp;
			$returnarray[$k][7] = $alliance;
			$k++;
		}
	}
	
	return $returnarray;
}

function isWithinPercent($top, $test, $percent) {
	$max = (QueryBuilder::getCountOfQuestionsForCurrentElection() * 2) + (Config::number_of_important_questions * 2);
		
	$top = getPercentage($top);
	$test = getPercentage($test);
	
	/*echo '>' . $max . '<br/>';
	echo '>>' . $percent . '<br/>';
	echo '>>>' . $test . '<br/>';
	echo '>>>>' . $top . '<br/>';*/
	
	if($top - $test > $percent)
		return false;
		
	return true;
	
	/*
	// why not without the max (old test): 
	$per = ($test + $max) / ($top + $max);
	// because this gives divide by 0 errors in certain cases
	
	echo '>' . $max . '<br/>';
	echo '>>' . $percent . '<br/>';
	echo '>>>' . $test . '<br/>';
	echo '>>>>' . $top . '<br/>';
	echo '>>>>>' . $per . '<br/>';
	
	if($per < $percent)
		return false;
		
	return true;*/
}

// translate a total to a success percentage
function getPercentage($total) {
	$max = (QueryBuilder::getCountOfQuestionsForCurrentElection() * 2) + (Config::number_of_important_questions * 2);
	$total = ($total + $max) / 2;
	$percentage =  round($total / $max * 100);
	
	return $percentage;
}
?>